package com.dylovedz.javafxphone.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.SaveFormat;
import com.dylovedz.javafxphone.controller.vo.WechatExcelVO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.BufferedOutputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Component
public class WechatService {

    public void saveHtml2Word(String path, WechatExcelVO article) throws Exception {

        //导出源内容
        /*String textFileName = path +  File.separator + index + ".txt";
        BufferedOutputStream textOutputStream = FileUtil.getOutputStream(textFileName);
        IoUtil.write(textOutputStream, true, article.getContent().getBytes(StandardCharsets.UTF_8));*/

        // 设置图片地址
        Document document = Jsoup.parse(article.getContent());
        Elements imgs = document.getElementsByTag("img");
        for (Element img : imgs) {
            img.attr("src", img.attr("data-src"));
        }
        article.setContent(document.html() + "<style> img {max-width: 100%}</style>");

        // 导出html
        /*String fileName = path +  File.separator + index + ".html";
        BufferedOutputStream outputStream = FileUtil.getOutputStream(fileName);
        IoUtil.write(outputStream, true, article.getContent().getBytes(StandardCharsets.UTF_8));*/

        // 导出world
        com.aspose.words.Document doc = new com.aspose.words.Document();
        DocumentBuilder documentBuilder = new DocumentBuilder(doc);
        documentBuilder.insertHtml(article.getContent());
        String order = article.getOrder() > 0 ? "_" + article.getOrder() : "";
        String worldFileName = path +  File.separator + article.getOffset() + order + ".docx";
        doc.save(worldFileName, SaveFormat.DOCX);
    }
}
